﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Net;
using System.IO;
using Common;

namespace ConsoleApplication1.TestThread
{
    public class Thread4
    {
        public static void Main()
        {
            try
            { 
              ThreadPool.SetMaxThreads(1000, 1000);
              Request();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
          
            Console.ReadKey();
            Console.Read();
        }

        static void Request()
        {
            ThreadPoolMessage("start");
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:7741/Handler.ashx");
            hwr.Method = "post";
            IAsyncResult result = hwr.BeginGetRequestStream(new AsyncCallback(EndGetRequestStream),hwr);
        }

        static void EndGetRequestStream(IAsyncResult iasync)
        {
            ThreadPoolMessage("RequestStream Complete");
            //获取HttpRequestStream
            if (iasync.IsCompleted)
            {
                Console.WriteLine("请求完成");
            }

            if (iasync.AsyncState == null)
            {
                Console.WriteLine("请求失败");
                return;
            }
            HttpWebRequest hwr = (HttpWebRequest)iasync.AsyncState;
            Stream stream = hwr.EndGetRequestStream(iasync);

            //写入请求条件
            byte[] condition = Encoding.UTF8.GetBytes("ID:1");
            stream.Write(condition, 0, condition.Length);
            //异步接收回传信息
            IAsyncResult iasy = hwr.BeginGetResponse(new AsyncCallback(EndGetResponseStream), hwr);
        }

        static void EndGetResponseStream(IAsyncResult iasync)
        {
            ThreadPoolMessage("GetResponse Complete");
            HttpWebRequest HWR = (HttpWebRequest)iasync.AsyncState;
            WebResponse WR = HWR.EndGetResponse(iasync);

            //将输出结果转换为Person对象
            Stream s = WR.GetResponseStream();
            BinaryFormatter bf = new BinaryFormatter();
            var person =(Person)bf.Deserialize(s);
            Console.WriteLine(string.Format("Person    Id:{0} Name:{1} Age:{2}",person.ID, person.name, person.age));
        }

        static void ThreadPoolMessage(string data)
        {
            int a, b;
            ThreadPool.GetAvailableThreads(out a, out b);
            string message = string.Format(@"{0}\n CurrentThreadID is {1}\n  workThreadId is {2} \n CompletionPointThreads is {3}\n",
                data,Thread.CurrentThread.ManagedThreadId,a.ToString(),b.ToString());
            Console.WriteLine(message);
        }
    }
}


